package lq.auth.studyauth.configure;

import lq.auth.studyauth.properties.StudyAuthProperties;
import lq.common.handler.StudyAccessDeniedHandler;
import lq.common.handler.StudyAuthExceptionEntryPoint;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 资源服务器配置类
 * FebsResourceServerConfigure用于处理非/oauth/开头的请求，
 * 其主要用于资源的保护，客户端只能通过OAuth2协议发放的令牌来从资源服务器中获取受保护的资源。
 * 因为在启动类中注入了@EnableStudyAuthExceptionHandler
 * 在@EnableStudyAuthExceptionHandler中@import了配置资源
 * 采用这样的方式将类注入到ioc容器中
 */
@Configuration
@EnableResourceServer //开启资源服务器相关配置
public class StudyResourceServerConfigure extends ResourceServerConfigurerAdapter {

    @Autowired
    private StudyAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private StudyAuthExceptionEntryPoint authExceptionEntryPoint;
    @Autowired
    private StudyAuthProperties properties;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 获取忽略验证路径,设置没有验证也可以通过访问,在多个的时候,配置文件中以逗号分隔
        String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");
        // requestMatchers().antMatchers("/**")的配置表明该安全配置对所有请求都生效
        // 通过.antMatchers(anonUrls).permitAll()配置免认证资源
        http.csrf().disable().requestMatchers().antMatchers("/**").and().authorizeRequests().antMatchers(anonUrls).permitAll().antMatchers("/**").authenticated();
    }

    /**
     * 重写异常处理
     *
     * @param resource
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resource) {
        resource.authenticationEntryPoint(authExceptionEntryPoint).accessDeniedHandler(accessDeniedHandler);
    }
}
